package vectorindex_v2

import (
	"context"
	"fmt"

	"github.com/milvus-io/milvus-sdk-go/v2/entity"
)

// IndexerType 索引器类型枚举
type IndexerType string

const (
	// IndexerTypeMilvus Milvus索引器类型
	IndexerTypeMilvus IndexerType = "milvus"
	// IndexerTypeFaiss Faiss索引器类型
	IndexerTypeFaiss IndexerType = "faiss"
)

// RetrieverType 检索器类型枚举
type RetrieverType string

const (
	// RetrieverTypeMilvus Milvus检索器类型
	RetrieverTypeMilvus RetrieverType = "milvus"
	// RetrieverTypeFaiss Faiss检索器类型
	RetrieverTypeFaiss RetrieverType = "faiss"
)

// CreateVectorIndexer 创建向量索引器
func CreateVectorIndexer(ctx context.Context, indexerType IndexerType, config interface{}) (VectorIndexer, error) {
	switch indexerType {
	case IndexerTypeMilvus:
		milvusConfig, ok := config.(*MilvusIndexerConfig)
		if !ok {
			return nil, fmt.Errorf("invalid MilvusIndexerConfig type")
		}
		return NewMilvusIndexer(ctx, milvusConfig)
	case IndexerTypeFaiss:
		faissConfig, ok := config.(*FaissIndexerConfig)
		if !ok {
			return nil, fmt.Errorf("invalid FaissIndexerConfig type")
		}
		return NewFaissIndexer(ctx, faissConfig)
	default:
		return nil, fmt.Errorf("unsupported indexer type: %s", indexerType)
	}
}

// CreateVectorRetriever 创建向量检索器
func CreateVectorRetriever(ctx context.Context, retrieverType RetrieverType, config interface{}) (VectorRetriever, error) {
	switch retrieverType {
	case RetrieverTypeMilvus:
		milvusConfig, ok := config.(*MilvusRetrieverConfig)
		if !ok {
			return nil, fmt.Errorf("invalid MilvusRetrieverConfig type")
		}
		return NewMilvusRetriever(ctx, milvusConfig)
	case RetrieverTypeFaiss:
		faissConfig, ok := config.(*FaissRetrieverConfig)
		if !ok {
			return nil, fmt.Errorf("invalid FaissRetrieverConfig type")
		}
		return NewFaissRetriever(ctx, faissConfig)
	default:
		return nil, fmt.Errorf("unsupported retriever type: %s", retrieverType)
	}
}

// CreateDefaultMilvusConfig 创建默认的Milvus配置
func CreateDefaultMilvusConfig(address, collectionName string, vectorDim int) *MilvusIndexerConfig {
	return &MilvusIndexerConfig{
		Address:        address,
		CollectionName: collectionName,
		VectorDim:      vectorDim,
		MetricType:     entity.L2,
		IndexType:      entity.IndexHNSW,
		IndexParams: map[string]interface{}{
			"M":              16,
			"efConstruction": 200,
		},
		BatchSize: 100,
	}
}

// CreateDefaultFaissConfig 创建默认的Faiss配置
func CreateDefaultFaissConfig(vectorDim int, indexPath, docPath string) *FaissIndexerConfig {
	return &FaissIndexerConfig{
		VectorDim:     vectorDim,
		IndexType:     "Flat",
		MetricType:    1, // L2 distance
		IndexPath:     indexPath,
		DocPath:       docPath,
		MaxCachedDocs: 10000,
	}
}
